package com.example.mylibrary.net.request;

import android.text.TextUtils;

import java.net.URLEncoder;
import java.util.HashMap;

public class QQVideoRequest {
    private static StringBuilder mBuilder = new StringBuilder();

    // API
    private static final String API = "http://tv.aiseet.atianqi.com/i-tvbin/qtv_video/search/get_search_all_type";
    // QUA标识
    private static final String QUA = URLEncoder.encode("PT=SNMAPP&CHID=16141");

    // 直接传入目标URL
    private String mUrl;
    // 组建参数列表
    private HashMap<String, String> mParams;

    // 是否修改参数的标识
    // 作用在直接传入目标URL但又需要修改参数
    private boolean isEdited = false;

    /**
     * 使用搜索关键字参数创建一个实例
     *
     * @param keyword 搜索关键字
     */
    public static QQVideoRequest createByKeyword(String keyword) {
        QQVideoRequest r = new QQVideoRequest();
        HashMap<String, String> params = new HashMap<>();
        params.put("api", API);
        params.put("key", keyword);
        params.put("tabid", "0");
        params.put("page_num", "0");
        params.put("page_size", "12");
        params.put("Q-UA", QUA);
        params.put("format", "json");
        params.put("is_filter_pay", "0");
        params.put("is_filter_video", "1");
        params.put("has_menu", "0");
        r.mParams = params;
        return r;
    }

    /**
     * 使用链接参数创建一个实例
     *
     * @param url 搜索关键字
     */
    public static QQVideoRequest createByURL(String url) {
        QQVideoRequest r = new QQVideoRequest();
        r.mUrl = url;
        return r;
    }

    private QQVideoRequest() {
    }

    /**
     * 修改参数
     */
    private void edit(String key, String value) {
        // 有数据时表示通过传入关键字创建
        // 或通过Url创建并已被转换为Map
        if (mParams != null) {
            mParams.put(key, value);
            return;
        }

        // 否则通过Url创建，且未经编辑，未转化为Map
        if (!TextUtils.isEmpty(mUrl)) {
            // 修改前数据校验，无需修改则取消操作
            String kv = key + "=" + URLEncoder.encode(value);
            if (mUrl.contains(kv)) {
                return;
            }
            // Url转化为Map并修改对应属性
            mParams = convertUrlToMap(mUrl);
            mParams.put(key, value);
        }
    }

    /**
     * 是否包含付费视频
     */
    public void containVIP(boolean flag) {
        edit("is_filter_pay", flag ? "0" : "1");
    }

    /**
     * 是否包含付费视频
     */
    public void setType(int type) {
        edit("tabid", String.valueOf(type));
    }

    /**
     * 设置页码
     */
    public void setPageIndex(int index) {
        edit("page_num", String.valueOf(index));
    }

    /**
     * 设置页容量
     */
    public void setPagerSize(int size) {
        edit("page_size", String.valueOf(size));
    }

    /**
     * 生成URL
     */
    public String buildUrl() {
        if (mParams != null) {
            return buildParams();
        } else {
            return (mUrl.contains("http") ? "" : "http://") + mUrl;
        }
    }

    /**
     * 通过Map生成Url
     */
    private String buildParams() {
        StringBuilder builder = mBuilder;
        HashMap<String, String> params = mParams;
        String api;

        builder.setLength(0);
        api = params.containsKey("api") ? params.remove("api") : API;
        builder.append(api).append("?");

        for (String key : params.keySet()) {
            builder.append(key).append("=");
            builder.append(params.get(key)).append("&");
        }
        builder.deleteCharAt(builder.length() - 1);

        params.put("api", api);
        return builder.toString();
    }

    /**
     * Url转换为可修改的Map
     */
    private static HashMap<String, String> convertUrlToMap(String url) {
        StringBuilder builder = mBuilder;
        HashMap<String, String> params = new HashMap<>();

        builder.setLength(0);
        builder.append(url);
        int index = builder.indexOf("?");
        if (index >= 0) {
            builder.delete(index, builder.length());
            if (builder.indexOf("http") < 0) {
                builder.insert(0, "http://");
            }
            params.put("api", builder.toString());
        }

        builder.setLength(0);
        builder.append(url, index + 1, url.length());
        String[] split = builder.toString().split("&");
        for (String kv : split) {
            String[] kvSplit = kv.split("=");
            if (kvSplit.length == 2) {
                params.put(kvSplit[0], kvSplit[1]);
            }
        }
        return params;
    }
}
